// 引入刚刚建立连接mysql数据库的db.js文件
const db = require('../config/db');
// 引入Sequelize对象
const Sequelize = db.sequelize;
// 引入上一步的数据表模型文件
const User = Sequelize['import']('../models/user');
// 自动创建表
User.sync({ force: true });

class UserModel {

  /**
   * 用户注册
   * @param data
   * @returns {Promise<boolean>}
   */
  static async createUser (data) {
    let result = await User.findOne({
      where: {
        name: data.name
      }
    });
    if (!result) {
      await User.create({
        name: data.name,
        password: data.password,
        token: data.token
      });
      return true;
    } else {
      return false;
    }
  }

  /**
   * 用户登录
   * @param req
   * @returns {Promise<Model>}
   */
  static async getUser (req) {
    return await User.findOne({
      attributes: ['id', 'name', 'roleId'],
      where: {
        name: req.name,
        password: req.password
      }
    });
  }

  /**
   * 删除用户
   * @param req
   * @returns {Promise<boolean>}
   */
  static async deleteUser (req) {
    let data = await User.destroy({
      where: {
        id: req
      }
    });
    return !!data;
  }

  /**
   * 查询所有用户
   * @param req
   * @returns {Promise<{rows: Model[]; count: number}>}
   */
  static async getUserList (req) {
    return await User.findAndCountAll({
      order: [
        ['id', 'desc']
      ],
      attributes: {exclude: ['token', 'password']},
      offset: (req.page - 1) * req.limit,
      limit: req.limit
    });
  }

  /**
   * 查询用户--根据角色
   * @param req
   * @returns {Promise<{rows: Model[]; count: number}>}
   */
  static async getUserByRole (req) {
    return await User.findAndCountAll({
      order: [
        ['id', 'desc']
      ],
      attributes: {exclude: ['token', 'password']},
      where: {
        roleId: req.roleId
      },
      offset: (req.page - 1) * req.limit,
      limit: req.limit
    });
  }
}

module.exports = UserModel;
